package cn.acewill.yxd.yunxundian.adapter;

import android.app.Activity;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;


import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;

import org.xutils.DbManager;
import org.xutils.ex.DbException;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import cn.acewill.yxd.yunxundian.BaseActivity;
import cn.acewill.yxd.yunxundian.R;
import cn.acewill.yxd.yunxundian.YXDAPP;
import cn.acewill.yxd.yunxundian.componet.MyScrollGridView;
import cn.acewill.yxd.yunxundian.model.ChongFuKouFen;
import cn.acewill.yxd.yunxundian.model.RMain;
import cn.acewill.yxd.yunxundian.model.tempLostRR;
import cn.acewill.yxd.yunxundian.ui.MainActivity;
import cn.acewill.yxd.yunxundian.utils.MaterialDialogUtils;
import cn.acewill.yxd.yunxundian.utils.SoftKeyBoardListener;
import cn.carbs.android.expandabletextview.library.ExpandableTextView;

/**
 * Created by xxx on 2018/1/16.
 */

public class EditEvaAdapter extends RecyclerView.Adapter<EditEvaAdapter.ViewHoler>{
    protected YXDAPP yxdapp=new YXDAPP();
    protected DbManager db = x.getDb(yxdapp.getDaoConfig());
    private String TAG = "EditEvaAdapter";
    private Context mContext;
    private List<RMain.TablesBean.RowsBean.Q2Bean> dataList;
    private OnItemClickListener clickListener;
    private List<RMain> rMains;
    private int schId;
    private SparseArray<Integer> mPositionsAndStates = new SparseArray<>();
    private List<ChongFuKouFen> kouFenList = new ArrayList<>();


    public EditEvaAdapter(Context mContext,int schId,List<RMain>rMains,List<RMain.TablesBean.RowsBean.Q2Bean> dataList,OnItemClickListener clickListener){
        this.mContext = mContext;
        this.schId = schId;
        this.dataList = dataList;
        this.clickListener = clickListener;
        this.rMains = rMains;
    }

    public void getChongFu(List<ChongFuKouFen> chongFuKouFens){
        this.kouFenList = chongFuKouFens;
    }

    @Override
    public ViewHoler onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.project_item_view,parent,false);

        return new ViewHoler(view);
    }
    //只要在getview时为其赋值为准确的宽度值即可，无论采用何种方法
    private int etvWidth;

    @Override
    public void onBindViewHolder(final ViewHoler holder, final int position) {
        final RMain.TablesBean.RowsBean.Q2Bean q2 = dataList.get(position);
        holder.bigTag(q2);
        if (q2.getSName()!=null&&!q2.getSName().equals("")){
            holder.q2Name.setText(q2.getSName()+"."+q2.getReportRowName());
        } else {
            holder.q2Name.setText(q2.getReportRowName());
        }
        if(etvWidth == 0){
            holder.q2Name.post(new Runnable() {
                @Override
                public void run() {
                    etvWidth = holder.q2Name.getWidth();
                }
            });
        }
        if (position ==dataList.size()-1){
            holder.dividerView.setVisibility(View.GONE);
        }
        holder.q2Name.setExpandListener(new ExpandableTextView.OnExpandListener() {
            @Override
            public void onExpand(ExpandableTextView view) {
                Object obj = view.getTag();
                if(obj != null && obj instanceof Integer){
                    mPositionsAndStates.put((Integer)obj, view.getExpandState());
                }
            }
            @Override
            public void onShrink(ExpandableTextView view) {
                Object obj = view.getTag();
                if(obj != null && obj instanceof Integer){
                    mPositionsAndStates.put((Integer)obj, view.getExpandState());
                }
            }
        });
        Integer state = mPositionsAndStates.get(position);
        String name = q2.getSName()+"."+q2.getReportRowName();
        holder.q2Name.updateForRecyclerView(name,etvWidth,state== null ? 0 : state);

        if (q2.getIsPoint()>=2){
            holder.pointView.setVisibility(View.VISIBLE);
        }else{
            holder.pointView.setVisibility(View.GONE);
        }

        final tempLostRR  rr;
        final List<RMain.TablesBean.RowsBean.RItemsBean>rowsBeans = getItemsByRrowid(q2.getID());
        try {
            rr = db.selector(tempLostRR.class).where("schId","=",schId).and("rRowId","=",q2.getID()).findFirst();
            if (rr!=null){
                if (!TextUtils.isEmpty(rr.getDescStr()))
                    holder.evaDesc.setVisibility(View.VISIBLE);
                else holder.evaDesc.setVisibility(View.GONE);
                holder.evaDesc.setText(rr.getDescStr());
                if (rr.getJpgStr()!=null&&rr.getJpgStr().length()>0){
                    String[] jpgStr = rr.getJpgStr().split(",");
                    holder.addPicture.setText("图片("+jpgStr.length+")");
                }else{
                    holder.addPicture.setText(R.string.picture_str);
                }
                if (rr.getVideoStr()!=null&&rr.getVideoStr().length()>0){
                    String[] videoStr = rr.getVideoStr().split(",");
                    holder.addVideo.setText("视频("+videoStr.length+")");
                }else{
                    holder.addVideo.setText(R.string.video_str);
                }
                if (rr.getScoreType()==1){
                    for (int k = 0;k<getItemsByRrowid(q2.getID()).size();k++){
                        if (getItemsByRrowid(q2.getID()).get(k).getID()==rr.getSelectItemId()){
                            getItemsByRrowid(q2.getID()).get(k).setCheck(true);
                            break;
                        }
                    }
                }

            }else{
                holder.addPicture.setText(R.string.picture_str);
                holder.addVideo.setText(R.string.video_str);
                holder.evaDesc.setVisibility(View.GONE);
            }
            //判断分数选择的类型
            if (TextUtils.isEmpty(q2.getItemType()+"")||q2.getItemType()==1){
                //单选
                holder.scoreList.setVisibility(View.VISIBLE);
                holder.inputScore.setVisibility(View.GONE);

                final ScoreCheckBoxAdapter adapter = new ScoreCheckBoxAdapter(mContext,q2,rowsBeans,schId);
                holder.scoreList.setAdapter(adapter);
                holder.scoreList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position1, long id) {
                        int index = -1;
                        for (int k = 0 ;k<rowsBeans.size();k++){

                            if (rowsBeans.get(k).isCheck()){
                                index = k;
                            }
                            rowsBeans.get(k).setCheck(false);
                        }
                        if(position1 == index){
                            rowsBeans.get(position1).setCheck(true);
//                            if (rr!=null){
//                                    //友情提示是否删除
//                                    showDeleteTip(rr);
////                                    db.delete(rr);
////                                    BaseActivity.showToast(mContext,"删除成功");
//                            }else{
//                                BaseActivity.showToast(mContext,"error");
//                            }
                        }else {
                            rowsBeans.get(position1).setCheck(true);
                            //当前项选中存储
                            double score = rowsBeans.get(position1).getScore();
                            int scoreId = rowsBeans.get(position1).getID();
                            int scoreType = 1;
                            if (q2.getItemType()==1||TextUtils.isEmpty(q2.getItemType()+"")){
                                scoreType = 1;
                            }else{
                                scoreType = q2.getItemType();
                            }
                            if (rr!=null){
                                rr.setScore(score);
                                rr.setSelectItemId(scoreId);
                                try {
                                    db.saveOrUpdate(rr);
                                } catch (DbException e) {
                                    e.printStackTrace();
                                }
                            }else{

                                tempLostRR cTemp = new tempLostRR(
                                        MainActivity.id,
                                        schId,
                                        q2.getID(),
                                        score,
                                        scoreId,
                                        BaseActivity.getNowDate(),
                                        "",
                                        "",
                                        q2.getReportRowName(),
                                        scoreType,
                                        "",
                                        true,
                                        q2.getIsPoint()
                                );
                                try {
                                    db.saveOrUpdate(cTemp);
                                } catch (DbException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                        Log.e("=adapterPosition====",position1+"");
                        clickListener.onAddScoreClick(dataList);
                        notifyItemChanged(position);

                        //    adapter.notifyDataSetChanged();
                    }
                });
            }else if (q2.getItemType() ==2){
                //输入,先移监听器
                if (holder.inputScore.getTag() instanceof TextWatcher){
                    holder.inputScore.removeTextChangedListener((TextWatcher)(holder.inputScore.getTag()));
                }
                //设置初始值
                Log.e(TAG, "afterTextChanged: q2id1 "+q2.getID() );
                holder.scoreList.setVisibility(View.GONE);
                holder.inputScore.setVisibility(View.VISIBLE);
                holder.inputScore.setHint("请输入分数："+"(总分："+q2.getMaxScore()+")");
                if (rMains.get(0).getQ().getCountFunc()==3){
                    holder.inputScore.setText("");
                }
                if (rr!=null){
                    holder.inputScore.setText(rr.getScore()+"");
                }


                TextWatcher watcher = new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {

                    }

                    @Override
                    public void afterTextChanged(Editable s) { //输入分值
                        double score = 0;
                        tempLostRR rr = null;
                        try {
                            rr = db.selector(tempLostRR.class).where("schId","=",schId).and("rRowId","=",q2.getID()).findFirst();
                            Log.e(TAG, "afterTextChanged: q2id "+q2.getID());
                            if (!TextUtils.isEmpty(s.toString())&&!s.toString().equals("0.0")){
                                score  = Double.parseDouble(s.toString());
                            }else{
                                score = 0;
                            }
                            if (q2.getMaxScore()<score){
                                BaseActivity.showToast(mContext,"请输入小与"+q2.getMaxScore()+"的分值");
                                //显示上一次的分值
                                holder.inputScore.setText("");
                            }else{
                                if (rr!=null){
                                    Log.e("rr!=null",rr.toString());
                                    rr.setScore(score);
                                    rr.setSelectItemId(0);
                                    try {
                                        db.saveOrUpdate(rr);
                                        Log.e(TAG, "afterTextChanged:rr "+rr );
                                        clickListener.onInputScoreListener(dataList);
                                    } catch (DbException e) {
                                        e.printStackTrace();
                                    }
                                }else{
                                    tempLostRR cTemp = new tempLostRR(
                                            MainActivity.id,
                                            schId,
                                            q2.getID(),
                                            score,
                                            0,
                                            BaseActivity.getNowDate(),
                                            "",
                                            "",
                                            q2.getReportRowName(),
                                            2,
                                            "",
                                            true,
                                            q2.getIsPoint()
                                    );
                                    try {
                                        Log.e("rr!=null",cTemp.toString());
                                        db.saveOrUpdate(cTemp);
                                        clickListener.onInputScoreListener(dataList);
                                    } catch (DbException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }

                        } catch (DbException e) {
                            e.printStackTrace();
                        }

                    }
                };
                holder.inputScore.addTextChangedListener(watcher);
                holder.inputScore.setTag(watcher);
//                SoftKeyBoardListener.setListener((Activity) mContext, new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() {
//                    @Override
//                    public void keyBoardShow(int height) {
//                    }
//                    @Override
//                    public void keyBoardHide(int height) {
//                        try {
//                            tempLostRR rr = db.selector(tempLostRR.class).where("schId","=",schId).and("rRowId","=",q2.getID()).findFirst();
//                            if (rr!=null){
//                                holder.inputScore.setText(String.valueOf(rr.getScore()));
//                                //清除焦点
//                                holder.inputScore.clearFocus();
//                            }
//                        } catch (DbException e) {
//                            e.printStackTrace();
//                        }
//                    }
//                });
            }else{
                //itemtype = 0 不需要显示分值，直接存储rr
                holder.inputScore.setVisibility(View.GONE);
                holder.scoreList.setVisibility(View.GONE);
                Log.e("score1",q2.getMaxScore()+"");
                tempLostRR typeRR = db.selector(tempLostRR.class).where("schId","=",schId).and("rRowId","=",q2.getID()).findFirst();
                if (typeRR==null){
                    typeRR = new tempLostRR(
                            MainActivity.id,
                            schId,
                            q2.getID(),
                            q2.getMaxScore(),
                            0,
                            BaseActivity.getNowDate(),
                            "",
                            "",
                            q2.getReportRowName(),
                            0,
                            "",
                            true,
                            q2.getIsPoint()
                    );
                    db.saveOrUpdate(typeRR);
                    Log.e("score2",q2.getMaxScore()+"");
                }
            }
            holder.koufenLinear.setVisibility(View.GONE);
            if (kouFenList!=null&&kouFenList.size()>0){
                for (ChongFuKouFen kouFen:kouFenList){
                    if (kouFen.getRrid() == q2.getID()){
                        holder.koufenLinear.setVisibility(View.VISIBLE);
                        break;
                    }
                }
            }
            //点击时间处理
            holder.addBackUp.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    clickListener.onBackUpClick(q2);
                }
            });
            holder.addPicture.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    clickListener.onAddPictureClick(q2);
                }
            });
            holder.addVideo.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    clickListener.onAddVideoClick(q2);
                }
            });

        } catch (DbException e) {
            e.printStackTrace();
        }

    }

    @Override
    public int getItemCount() {
        return dataList!=null? dataList.size():0;
    }

    class ViewHoler extends RecyclerView.ViewHolder {
        ExpandableTextView q2Name;
        TextView addBackUp;
        TextView addPicture;
        TextView addVideo;
        TextView evaDesc;
        EditText inputScore;
        MyScrollGridView scoreList;
        LinearLayout recordRel;
        TextView repeatLost;
        ImageView pointView;
        LinearLayout koufenLinear;
        View dividerView;
        private ViewHoler(View itemView) {
            super(itemView);
            q2Name = itemView.findViewById(R.id.q2Name);
            addBackUp = itemView.findViewById(R.id.addBackUp);
            addPicture = itemView.findViewById(R.id.addPicture);
            addVideo = itemView.findViewById(R.id.addVideo);
            evaDesc = itemView.findViewById(R.id.evaDesc);
            inputScore = itemView.findViewById(R.id.inputScore);
            scoreList = itemView.findViewById(R.id.scoreList);
            recordRel = itemView.findViewById(R.id.recordRel);
            repeatLost = itemView.findViewById(R.id.repeatLost);
            pointView = itemView.findViewById(R.id.pointView);
            koufenLinear = itemView.findViewById(R.id.koufenLinear);
            dividerView = itemView.findViewById(R.id.dividerView);
        }
        private void bigTag(RMain.TablesBean.RowsBean.Q2Bean q2Bean){
            addBackUp.setTag(q2Bean);
            addPicture.setTag(q2Bean);
            addVideo.setTag(q2Bean);
            q2Name.setTag(q2Bean);
        }
    }

    public interface OnItemClickListener{
        void onBackUpClick(RMain.TablesBean.RowsBean.Q2Bean q2Bean);
        void onAddPictureClick(RMain.TablesBean.RowsBean.Q2Bean q2Bean);
        void onAddVideoClick(RMain.TablesBean.RowsBean.Q2Bean q2Bean);
        void onAddScoreClick(List<RMain.TablesBean.RowsBean.Q2Bean> q2Beans);
        void onInputScoreListener(List<RMain.TablesBean.RowsBean.Q2Bean> q2Beans);
    }

    private List<RMain.TablesBean.RowsBean.RItemsBean> getItemsByRrowid(int rowid) {
        List<RMain.TablesBean.RowsBean.RItemsBean> itemList = null;
        for (int i = 0; i < rMains.size(); i++) {
            List<RMain.TablesBean> tb = rMains.get(i).getTables();
            for (RMain.TablesBean t : tb) {
                List<RMain.TablesBean.RowsBean> rbs = t.getRows();
                for (RMain.TablesBean.RowsBean rb : rbs) {
                    if (rb.getQ2().getID() == rowid) {
                        itemList = rb.getRItems();
                        break;
                    }
                }
            }
        }
        return itemList;
    }


    private void showDeleteTip(final tempLostRR rr){
        MaterialDialogUtils.showMaterialDialog(mContext, "是否删除当前评估项", "删除", "取消", true, false,
                new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        try {
                            db.delete(rr);
                        } catch (DbException e) {
                            e.printStackTrace();
                        }
                    }
                }, new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        dialog.dismiss();
                    }
                });
    }

}
